package com.tn.service.weigh.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.gitee.hifong45.FE;
import com.gitee.hifong45.Kv;
import com.gitee.hifong45.Msg;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.listenvision.test;
import com.tn.controller.alarm.common.constants.Constants;
import com.tn.controller.alarm.common.enums.CommonCodeEnum;
import com.tn.controller.alarm.common.model.CommonVO;
import com.tn.controller.alarm.common.model.PageInput;
import com.tn.controller.alarm.common.model.PageResult;
import com.tn.controller.alarm.common.model.camera.vo.AreaVideoVO;
import com.tn.controller.alarm.common.model.camera.vo.CameraVO;
import com.tn.controller.alarm.common.model.cardrobot.CardSenderRobotInfoDO;
import com.tn.controller.alarm.common.model.external.producer.vo.WhiteListMemberVO;
import com.tn.controller.alarm.common.model.weigh.mq.LicenseDto;
import com.tn.controller.alarm.common.model.weigh.vo.WeighLogInfoVO;
import com.tn.controller.alarm.common.model.weigh.vo.WeighLogQueryVO;
import com.tn.dao.camera.ICameraDao;
import com.tn.dao.cardsender.CardSenderRobotDao;
import com.tn.dao.external.subsystem.IGateTruckDao;
import com.tn.dao.mbpdao.*;
import com.tn.dao.weigh.IWeighDao;
import com.tn.entity.QueryMessageVO;
import com.tn.entity.QueryWhiteVO;
import com.tn.exception.DatabaseOperationFailedException;
import com.tn.properties.WeighLedIpProperties;
import com.tn.service.cardrobot.impl.CardSendRobotServiceImpl;
import com.tn.service.weigh.IWeighService;

import com.tn.tcp.CardMachine;
import com.tn.tcp.CardMachineInData;
import com.tn.tcp.CardMachineParamUtil;
import com.tn.utils.JsonUtil;
import com.tn.vo.WeightLogMin;
import com.tn.websocket.WebSocket;
import io.minio.ObjectWriteResponse;

import lombok.extern.slf4j.Slf4j;
import lombok.var;


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import plus.ojbk.minio.core.MinioTemplate;

import javax.annotation.Resource;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

import java.lang.reflect.Field;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 磅房服务实现类
 *
 * @program: tn_aucy_java
 * @author: yangjiayao
 * @create: 2021/11/16
 */
@Slf4j
@Service
@Transactional
public class WeighServiceImpl implements IWeighService {
    /**
     * 磅房数据库交互Dao
     */

    @Autowired
    private IGateTruckDao iGateDao;


    private com.tn.dao.weigh.IWeighDao weighDao;

    @Resource
    private IWeighDao iWeighDao;
    @Resource
    public WeightloginfoMapper weightloginfoMapper;
    @Resource
    public WeightLogMinMapper weightLogMinMapper;

    @Autowired
    private CardSenderRobotDao cardSenderRobotDao;

    @Resource
    public TruckinfoMapper truckinfoMapper;

    @Autowired
    private ICameraDao cameraDao;

    @Autowired
    private MinioTemplate minioTemplate;


    @Value("${hkServer.client_id:''}")
    private String appKey;


    @Value("${hkServer.client_secret:''}")
    private String appSecret;

    public static ArtemisConfig artemisConfig;

    @Value("${card.id-correc-num:11}")
    private Integer cardIdCorrectNum; // 卡号应有的位


    @Resource
    private CardSendRobotServiceImpl cardSendRobotServiceImpl;


    @Autowired
    private WebSocket webSocket;


    @Autowired
    public void setWeighDao(com.tn.dao.weigh.IWeighDao weighDao) {
        this.weighDao = weighDao;
    }


    @Override
    public CommonVO<List<WeighLogInfoVO>> currentWeighInfo() {
        CommonVO<List<WeighLogInfoVO>> resultCommonVO = new CommonVO<>();
        List<WeighLogInfoVO> weighLogInfoVOS = weighDao.queryCurrentWeighLogInfoByPage();
        resultCommonVO.setData(weighLogInfoVOS);
        return resultCommonVO;
    }

//    /**
//     * @param curPage  当前页
//     * @param pageSize 页长
//     * @param queryVO  查询条件
//     * @return
//     */
//    @Override
//    public CommonVO<PageResult<WeighLogInfoVO>> getWeighLogInfo(Integer curPage, Integer pageSize,
//                                                                WeighLogQueryVO queryVO) {
//        CommonVO<PageResult<WeighLogInfoVO>> resultCommonVO = new CommonVO<>();
//        if (!StringUtils.isEmpty(queryVO.getWeightWhere())) {
//            String[] weightWhere = queryVO.getWeightWhere().split(",");
//            if (weightWhere.length > 1) {
//                queryVO.setWeight(Float.valueOf(weightWhere[1]));
//                queryVO.setCharCompare(weightWhere[0]);
//            }
//        }
//        int totalCount = weighDao.queryWeighLogInfoCount(queryVO);
//        PageResult<WeighLogInfoVO> result = new PageResult<>(curPage, pageSize, totalCount);
//        List<WeighLogInfoVO> weighLogInfoVOS = weighDao.queryWeighLogInfoByPage(result.getStartIndex(), pageSize, queryVO);
//        if(StringUtils.isNotBlank(queryVO.getOperateType()) && "QM".equals(queryVO.getOperateType())){
//            if(weighLogInfoVOS != null && !weighLogInfoVOS.isEmpty()){
//                WeighLogInfoVO weighLogInfoVO = weighLogInfoVOS.get(0);
//                if(weighLogInfoVO.getWeighTime() != null){
//                    try {
//                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                        Date parse = sdf.parse(weighLogInfoVO.getWeighTime());
//                        long betweenMs = DateUtil.betweenMs(parse, new Date());
//                        if(betweenMs / 1000 / 60 > 10){
//                             resultCommonVO.setMsg("数据正在保存中,请稍后再试...");
////                            throw new BaseException(500,"当前过磅信息未保存完毕，请稍后重试！");
//                        }
//                    } catch (ParseException e) {
//                        throw new BaseException(500,"查询数据失败，请稍后重试！");
//                    }
//                }
//            }
//        }
//        result.setData(weighLogInfoVOS);
//        resultCommonVO.setData(result);
//        return resultCommonVO;
//    }


        /**
     * @param curPage  当前页
     * @param pageSize 页长
     * @param queryVO  查询条件
     * @return
     */
    @Override
    public CommonVO<PageResult<WeighLogInfoVO>> getWeighLogInfo(Integer curPage, Integer pageSize,
                                                                WeighLogQueryVO queryVO) {
        CommonVO<PageResult<WeighLogInfoVO>> resultCommonVO = new CommonVO<>();
        if (!StringUtils.isEmpty(queryVO.getWeightWhere())) {
            String[] weightWhere = queryVO.getWeightWhere().split(",");
            if (weightWhere.length > 1) {
                queryVO.setWeight(Float.valueOf(weightWhere[1]));
                queryVO.setCharCompare(weightWhere[0]);
            }
        }
            int totalCount = weighDao.queryWeighLogInfoCount(queryVO);
            PageResult<WeighLogInfoVO> result = new PageResult<>(curPage, pageSize, totalCount);
            result.setData(weighDao.queryWeighLogInfoByPage(result.getStartIndex(), pageSize, queryVO));
            resultCommonVO.setData(result);
//        Object isSaving = RedisUtils.getCacheObject("is_sgggg");
//        if(isSaving != null) {
//            resultCommonVO.setMsg("数据正在保存中，请稍后再试...");
//        }
        return resultCommonVO;
    }

    @Override
    public CommonVO<PageResult<WeighLogInfoVO>> queryWeighLogInfo(Integer curPage, Integer pageSize,
                                                                  WeighLogQueryVO queryVO) {
        CommonVO<PageResult<WeighLogInfoVO>> resultCommonVO = new CommonVO<>();
        if (!StringUtils.isEmpty(queryVO.getWeightWhere())) {
            String[] weightWhere = queryVO.getWeightWhere().split(",");
            if (weightWhere.length > 1) {
                queryVO.setWeight(Float.valueOf(weightWhere[1]));
                queryVO.setCharCompare(weightWhere[0]);
            }
        }
        int totalCount = weighDao.queryWeighLogInfoCount(queryVO);
        PageResult<WeighLogInfoVO> result = new PageResult<>(curPage, pageSize, totalCount);
        result.setData(weighDao.queryWeighLogInfoByPage(result.getStartIndex(), pageSize, queryVO));
        resultCommonVO.setData(result);
        return resultCommonVO;
    }


    @Override
    public Map<String, Object> stamp(Map<String, String> map) throws Exception {
        Long id = Long.valueOf(map.get("id"));
        //根据id查询称重单毛重
        WeighLogInfoVO vo = weighDao.queryWeighLogInfo(id);
        //毛重
        Float weight = vo.getWeight();
        String weighTime = vo.getWeighTime();

        WeighLogInfoVO weighLogInfoVO = weighDao.queryWeighLogInfoQP(vo);
        //空重
        Float weight1 = weighLogInfoVO.getWeight();
        String weighTime1 = weighLogInfoVO.getWeighTime();

        //净重
        float v = weight - weight1;
        //设置模板
        Map<String, Object> exportMap = new HashMap<>();
        exportMap.put("name", vo.getName());
        exportMap.put("uuid", "B" + System.currentTimeMillis());
        exportMap.put("license", vo.getLicense());
        exportMap.put("goodsName", vo.getGoodsName());
        exportMap.put("weight", weight);
        exportMap.put("weight1", weight1);
        exportMap.put("v", v);
        exportMap.put("weighTime", weighTime);
        exportMap.put("weighTime1", weighTime1);
        exportMap.put("consignCompanyName", vo.getConsignCompanyName());
        exportMap.put("shipNo", vo.getShipNo());
        exportMap.put("customerCompanyName", vo.getCustomerCompanyName());
        exportMap.put("userName", map.get("userName"));
        exportMap.put("weightId", vo.getWeighId());
//        String weighId = vo.getWeighId();
//        WordUtil.createWord(exportMap,"12345.ftl",filePath+weighId+".doc");
//        Document doc = new Document();
//        doc.loadFromFile(filePath + weighId+".doc");
//        doc.saveToFile(filePath + weighId+".pdf", FileFormat.PDF);
        return exportMap;

    }

    @Override
    public CommonVO<List<WeighLogInfoVO>> queryWeightSum(WeighLogQueryVO queryVO) {
        getSumWhereValueCondition(queryVO);
        List<WeighLogInfoVO> list = weighDao.queryWeighLogSumList(queryVO);
        CommonVO<List<WeighLogInfoVO>> resultCommonVO = new CommonVO<>();
        resultCommonVO.setData(list);
        return resultCommonVO;
    }

    private void getSumWhereValueCondition(WeighLogQueryVO queryVO) {
        Map<String, String> groupByConditionWhereValue = new HashMap<>();
        groupByConditionWhereValue.put("license", "");
        groupByConditionWhereValue.put("goodsName", "");
        groupByConditionWhereValue.put("customerCompanyName", "");
        groupByConditionWhereValue.put("consignCompanyName", "");
        groupByConditionWhereValue.put("shipNo", "");
        groupByConditionWhereValue.put("contractNo", "");
        groupByConditionWhereValue.put("cntrNo", "");
        groupByConditionWhereValue.put("cntrSizeType", "");
        groupByConditionWhereValue.put("poundNo", "");
        groupByConditionWhereValue.put("remark", "");
        if (queryVO.getGroupByConditionWhere() != null) {
            Map<String, Object> object = queryVO.getGroupByConditionWhere();
            if (!StringUtils.isEmpty(queryVO.getLicense()) && ("all".equals(queryVO.getLicense()))) {
                groupByConditionWhereValue.put("license", "all");
            }
            if (queryVO.getGroupByConditionWhere().containsKey("license")) {
                String license = object.get("license").toString();
                if (StringUtils.isNotEmpty(license)) {
                    groupByConditionWhereValue.put("license", license);
                }
            }
            if (queryVO.getGroupByConditionWhere().containsKey("goodsName")) {
                String goodsName = object.get("goodsName").toString();
                if (StringUtils.isNotEmpty(goodsName)) {
                    groupByConditionWhereValue.put("goodsName", goodsName);
                }
            }
            if (queryVO.getGroupByConditionWhere().containsKey("customerCompanyName")) {
                String customerCompanyName = object.get("customerCompanyName").toString();
                if (StringUtils.isNotEmpty(customerCompanyName)) {
                    groupByConditionWhereValue.put("customerCompanyName", customerCompanyName);
                }

            }
            if (queryVO.getGroupByConditionWhere().containsKey("consignCompanyName")) {
                String consignCompanyName = object.get("consignCompanyName").toString();
                if (StringUtils.isNotEmpty(consignCompanyName)) {
                    groupByConditionWhereValue.put("consignCompanyName", consignCompanyName);
                }
            }

            if (queryVO.getGroupByConditionWhere().containsKey("shipNo")) {
                String shipNo = object.get("shipNo").toString();
                if (StringUtils.isNotEmpty(shipNo)) {
                    groupByConditionWhereValue.put("shipNo", shipNo);
                }
            }
            if (queryVO.getGroupByConditionWhere().containsKey("contractNo")) {
                String contractNo = object.get("contractNo").toString();
                if (StringUtils.isNotEmpty(contractNo)) {
                    groupByConditionWhereValue.put("contractNo", contractNo);
                }
            }
            if (queryVO.getGroupByConditionWhere().containsKey("cntrNo")) {
                String cntrNo = object.get("cntrNo").toString();
                if (StringUtils.isNotEmpty(cntrNo)) {
                    groupByConditionWhereValue.put("cntrNo", cntrNo);
                }
            }
            if (queryVO.getGroupByConditionWhere().containsKey("cntrSizeType")) {
                String cntrSizeType = object.get("cntrSizeType").toString();
                if (StringUtils.isNotEmpty(cntrSizeType)) {
                    groupByConditionWhereValue.put("cntrSizeType", cntrSizeType);
                }
            }
            if (queryVO.getGroupByConditionWhere().containsKey("poundNo")) {
                String poundNo = object.get("poundNo").toString();
                if (StringUtils.isNotEmpty(poundNo)) {
                    groupByConditionWhereValue.put("poundNo", poundNo);
                }
            }
            if (queryVO.getGroupByConditionWhere().containsKey("remark")) {
                String remark = object.get("remark").toString();
                if (StringUtils.isNotEmpty(remark)) {
                    groupByConditionWhereValue.put("remark", remark);
                }
            }
        }
        queryVO.setGroupByConditionValue(groupByConditionWhereValue);
    }

    private void getSumWhereShowDetail(WeighLogQueryVO queryVO) {
        Map<String, String> groupByConditionValue = queryVO.getGroupByConditionValue();
        if (queryVO.getGroupByConditionWhere() != null) {
            if (!StringUtils.isEmpty(queryVO.getPreviewValue())) {
                groupByConditionValue.put(queryVO.getGroupBy(), queryVO.getPreviewValue());
            }
        }
        queryVO.setGroupByConditionValue(groupByConditionValue);
    }


    @Override
    public void exportWeighLogInfo(HttpServletRequest request, HttpServletResponse response, WeighLogQueryVO queryVO) throws IOException {
        if (!StringUtils.isEmpty(queryVO.getWeightWhere())) {
            String[] weightWhere = queryVO.getWeightWhere().split(",");
            if (weightWhere.length > 1) {
                queryVO.setWeight(Float.valueOf(weightWhere[1]));
                queryVO.setCharCompare(weightWhere[0]);
            }
        }
        List<WeighLogInfoVO> list = weighDao.queryWeighLogInfoList(queryVO);
        HSSFWorkbook workbook = new HSSFWorkbook();//创建HSSFWorkbook对象,  excel的文档对象
        HSSFSheet sheet = workbook.createSheet("磅房称重数据信息表"); //excel的表单
        String fileName = "CarWeightInfo" + ".xls";//设置要导出的文件的名字
        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        //String[] headers = {"序号", "磅房编号", "车牌号", "任务编号", "物流公司", "货品", "船号","皮重","毛重", "净重", "称重时间", "是否上报", "皮/毛"};
        String[] headers = {"序号", "磅房编号", "车牌号", "皮重(kg)", "毛重(kg)", "净重(kg)", "皮/毛", "过皮时间", "过毛时间", "任务编号", "货品", "船号", "货主单位", "物流公司", "合同号", "箱号", "箱型", "备注", "是否上报", "称重时间", "创建者", "修改者", "修改时间"};
        //headers表示excel表中第一行的表头
        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
        if (!CollectionUtils.isEmpty(list)) {
            //在表中存放查询到的数据放入对应的列
            for (WeighLogInfoVO teacher : list) {
                HSSFRow row1 = sheet.createRow(rowNum);
                Float weightStr = 0f;
                Float grossWeightStr = 0f;
                Float tareWeightStr = 0f;
                /*if (!Objects.isNull(teacher.getWeight())) {
                    weightStr = teacher.getWeight();
                }*/
                //皮重
                if (!Objects.isNull(teacher.getTareWeight())) {
                    tareWeightStr = teacher.getTareWeight();
                }
                //毛重
                if (!Objects.isNull(teacher.getGrossWeight())) {
                    grossWeightStr = teacher.getGrossWeight();
                }
                //净重
                if (!Objects.isNull(teacher.getTareWeight()) && teacher.getTareWeight() > 0) {
                    weightStr = grossWeightStr - tareWeightStr;
                }
                String reportResult = "";
                if (!Objects.isNull(teacher.getReportResult())) {
                    if (teacher.getReportResult().equals("1")) {
                        reportResult = "上报成功";
                    }
                    if (teacher.getReportResult().equals("pass")) {
                        reportResult = "删除";
                    }
                    if (teacher.getReportResult().equals("localSave")) {
                        reportResult = "本地保存";
                    }
                    if (teacher.getReportResult().equals("upFailed")) {
                        reportResult = "上报失败";
                    }
                }
                String operateType = "";
                if (!Objects.isNull(teacher.getOperateType())) {
                    if (teacher.getOperateType().equals("QP")) {
                        operateType = "皮重";
                    }
                    if (teacher.getOperateType().equals("QM")) {
                        operateType = "毛重";
                    }
                }
                row1.createCell(0).setCellValue(rowNum);
                row1.createCell(1).setCellValue(teacher.getName());
                row1.createCell(2).setCellValue(teacher.getLicense());
                if (tareWeightStr > 0) {
                    row1.createCell(3).setCellValue(tareWeightStr);
                }
                if (grossWeightStr > 0) {
                    row1.createCell(4).setCellValue(grossWeightStr);
                }
                if (weightStr > 0) {
                    row1.createCell(5).setCellValue(weightStr);
                }
                row1.createCell(6).setCellValue(operateType);
                row1.createCell(7).setCellValue(teacher.getTareWeighTime());
                row1.createCell(8).setCellValue(teacher.getGrossWeighTime());
                row1.createCell(9).setCellValue(teacher.getTaskNo());
                row1.createCell(10).setCellValue(teacher.getGoodsName());
                row1.createCell(11).setCellValue(teacher.getShipNo());
                row1.createCell(12).setCellValue(teacher.getCustomerCompanyName());
                row1.createCell(13).setCellValue(teacher.getConsignCompanyName());
                row1.createCell(14).setCellValue(teacher.getContractNo());
                row1.createCell(15).setCellValue(teacher.getCntrNo());
                row1.createCell(16).setCellValue(teacher.getCntrSizeType());
                row1.createCell(17).setCellValue(teacher.getRemark());
                row1.createCell(18).setCellValue(reportResult);
                row1.createCell(19).setCellValue(teacher.getWeighTime());
                row1.createCell(20).setCellValue(teacher.getCreator());
                row1.createCell(21).setCellValue(teacher.getUserName());
                row1.createCell(22).setCellValue(teacher.getUpdateTime());
                rowNum++;
            }
        }
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }


    @Override
    public void exportQueryWeightSum(HttpServletRequest request, HttpServletResponse response, WeighLogQueryVO queryVO) throws IOException {
        getSumWhereValueCondition(queryVO);
        List<WeighLogInfoVO> sumList = weighDao.queryWeighLogSumList(queryVO);
        HSSFWorkbook workbook = new HSSFWorkbook();//创建HSSFWorkbook对象,  excel的文档对象
        HSSFSheet sheet = workbook.createSheet("汇总称重数据表"); //excel的表单
        sheet.setDefaultColumnWidth(23);
        String fileName = "SumWeightInfo" + ".xls";//设置要导出的文件的名字
        sumOrDetailExcelData(queryVO, sumList, workbook, sheet);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

    private void sumOrDetailExcelData(WeighLogQueryVO queryVO, List<WeighLogInfoVO> sumList, HSSFWorkbook workbook, HSSFSheet sheet) {
        // 创建表头单元格样式
        HSSFCellStyle cs_header = getExcelHeadHssfCellStyle(workbook);
        HSSFCellStyle cs_body = getExcelBodyHssfCellStyle(workbook);
        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        String[] headers = querySumHeader(queryVO);
        //headers表示excel表中第一行的表头
        HSSFRow row = sheet.createRow(0);
        row.setHeightInPoints((short) 20);
        //在excel表中添加表头
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
            cell.setCellStyle(cs_header);
        }
        Cell cell = null;
        if (!CollectionUtils.isEmpty(sumList)) {
            double tareWeightSum = 0f;
            double grossWeightSum = 0f;
            double cargoWeightSum = 0f;
            int count = 0;
            // 在表中存放查询到的数据放入对应的列
            for (WeighLogInfoVO teacher : sumList) {
                //  不打印明细
                if (!"poundNo".equals(queryVO.getDetailFlag())) {
                    createNoDetailRows(teacher, sheet, rowNum, cs_body);
                    count = count + teacher.getCount();
                    grossWeightSum = grossWeightSum + teacher.getGrossWeight();
                    tareWeightSum = tareWeightSum + teacher.getTareWeight();
                    cargoWeightSum = cargoWeightSum + teacher.getCargoWeight();
                    rowNum++;
                }
                if ("poundNo".equals(queryVO.getDetailFlag())) {
                    WeighLogQueryVO detailQueryVo = getSumQueryVO(queryVO, teacher);
                    // 发货名称
                    HSSFRow row0 = sheet.createRow(rowNum);
                    row0.setHeightInPoints((short) 14);
                    cell = row0.createCell(0);
                    String teachers = teacher.getName();
                    if (StringUtils.isEmpty(teachers)) {
                        teachers = "空";
                    }
                    cell.setCellValue(detailQueryVo.getCellName() + "  " + teachers);
                    cell.setCellStyle(cs_body);
                    rowNum++;
                    rowNum = createHaveDetailRows(detailQueryVo, teacher, sheet, rowNum, cs_body);
                    grossWeightSum = grossWeightSum + teacher.getGrossWeight();
                    tareWeightSum = tareWeightSum + teacher.getTareWeight();
                    cargoWeightSum = cargoWeightSum + teacher.getCargoWeight();
                    rowNum++;
                }
            }
            HSSFRow row2 = sheet.createRow(rowNum);
            row2.setHeightInPoints((short) 14);
            cell = row2.createCell(0);
            cell.setCellValue("总计");
            cell.setCellStyle(cs_body);
            if (!"poundNo".equals(queryVO.getDetailFlag())) {
                cell = row2.createCell(1);
                setCellStyleAndType(cell, cs_body);
                cell.setCellValue(count);

            }
            if ("poundNo".equals(queryVO.getDetailFlag())) {
                cell = row2.createCell(1);
                cell.setCellStyle(cs_body);
                cell = row2.createCell(5);
                cell.setCellStyle(cs_body);
            }
            cell = row2.createCell(2);
            setCellStyleAndType(cell, cs_body);
            cell.setCellValue(grossWeightSum);
            cell = row2.createCell(3);
            setCellStyleAndType(cell, cs_body);
            cell.setCellValue(tareWeightSum);
            cell = row2.createCell(4);
            setCellStyleAndType(cell, cs_body);
            cell.setCellValue(cargoWeightSum);
        }
    }

    private void setCellStyleAndType(Cell cell, HSSFCellStyle cs_body) {
        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
        cell.setCellStyle(cs_body);
    }


    private HSSFCellStyle getExcelHeadHssfCellStyle(HSSFWorkbook workbook) {
        HSSFCellStyle cs_header = workbook.createCellStyle();
        Font boldFont = workbook.createFont();
        boldFont.setFontName("Consolas");
        boldFont.setBoldweight((short) 2);
        boldFont.setFontHeightInPoints((short) 14);
        cs_header.setFont(boldFont);
        cs_header.setBorderBottom((short) 1);
        cs_header.setBorderLeft((short) 1);
        cs_header.setBorderRight((short) 1);
        cs_header.setBorderTop((short) 1);
        cs_header.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        return cs_header;
    }

    private HSSFCellStyle getExcelBodyHssfCellStyle(HSSFWorkbook workbook) {
        HSSFCellStyle cs_header = workbook.createCellStyle();
        Font boldFont = workbook.createFont();
        boldFont.setFontName("Consolas");
        boldFont.setFontHeightInPoints((short) 11.5);
        cs_header.setFont(boldFont);
        cs_header.setBorderBottom((short) 1);
        cs_header.setBorderLeft((short) 1);
        cs_header.setBorderRight((short) 1);
        cs_header.setBorderTop((short) 1);
        cs_header.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        return cs_header;
    }

    private void createNoDetailRows(WeighLogInfoVO teacher, HSSFSheet sheet, int rowNum, HSSFCellStyle cs_body) {
        HSSFRow row1 = sheet.createRow(rowNum);
        row1.setHeightInPoints((short) 14);
        Float tareWeight = 0f;
        Float grossWeight = 0f;
        Float cargoWeight = 0f;
        Cell cell = null;
        if (!Objects.isNull(teacher.getGrossWeight())) {
            grossWeight = teacher.getGrossWeight();
        }
        if (!Objects.isNull(teacher.getTareWeight())) {
            tareWeight = teacher.getTareWeight();
        }
        if (!Objects.isNull(teacher.getCargoWeight())) {
            cargoWeight = teacher.getCargoWeight();
        }
        cell = row1.createCell(0);
        cell.setCellValue(teacher.getName());
        cell.setCellStyle(cs_body);
        cell = row1.createCell(1);
        cell.setCellValue(teacher.getCount());
        cell.setCellStyle(cs_body);
        cell = row1.createCell(2);
        setCellStyleAndType(cell, cs_body);
        cell.setCellValue(grossWeight);
        cell = row1.createCell(3);
        setCellStyleAndType(cell, cs_body);
        cell.setCellValue(tareWeight);
        cell = row1.createCell(4);
        setCellStyleAndType(cell, cs_body);
        cell.setCellValue(cargoWeight);
        rowNum++;
    }

    private int createHaveDetailRows(WeighLogQueryVO detailQueryVo, WeighLogInfoVO teacher, HSSFSheet sheet, int rowNum, HSSFCellStyle cs_body) {
        List<WeighLogInfoVO> detailList = weighDao.queryWeighLogSumDetailList(detailQueryVo);
        //先以属性一升序,升序结果进行属性一降序,再进行属性二降序
        detailList.sort(Comparator.comparing(person -> person.getWeighTime()));
        int licenceCount = 0;
        Cell cell = null;
        Float tareWeightSum = 0f;
        Float grossWeightSum = 0f;
        Float cargoWeightSum = 0f;
        for (WeighLogInfoVO detail : detailList) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.setHeightInPoints((short) 14);
            Float tareWeight = 0f;
            Float grossWeight = 0f;
            Float cargoWeight = 0f;
            if (!Objects.isNull(detail.getGrossWeight())) {
                grossWeight = detail.getGrossWeight();
                // grossWeightSum = grossWeightSum + grossWeight;
            }
            if (!Objects.isNull(detail.getTareWeight())) {
                tareWeight = detail.getTareWeight();
                // tareWeightSum =tareWeightSum +tareWeight;
            }
            if (!Objects.isNull(detail.getCargoWeight())) {
                cargoWeight = detail.getCargoWeight();
                //cargoWeightSum = cargoWeightSum +cargoWeight;
            }
            cell = row1.createCell(0);
            cell.setCellValue(detail.getName());
            cell.setCellStyle(cs_body);
            cell = row1.createCell(1);
            cell.setCellValue(detail.getLicense());
            cell.setCellStyle(cs_body);
            cell = row1.createCell(2);
            setCellStyleAndType(cell, cs_body);
            cell.setCellValue(grossWeight);
            cell = row1.createCell(3);
            setCellStyleAndType(cell, cs_body);
            cell.setCellValue(tareWeight);
            cell = row1.createCell(4);
            setCellStyleAndType(cell, cs_body);
            cell.setCellValue(cargoWeight);
            cell = row1.createCell(5);
            cell.setCellValue(detail.getWeighTime());
            cell.setCellStyle(cs_body);
            licenceCount++;
            rowNum++;
        }
        HSSFRow row2 = sheet.createRow(rowNum);
        row2.setHeightInPoints((short) 14);
        cell = row2.createCell(0);
        cell.setCellValue("小计");
        cell.setCellStyle(cs_body);
        cell = row2.createCell(1);
        cell.setCellValue(licenceCount);
        cell.setCellStyle(cs_body);
        cell = row2.createCell(2);
        setCellStyleAndType(cell, cs_body);
        cell.setCellValue(teacher.getGrossWeight());
        cell = row2.createCell(3);
        setCellStyleAndType(cell, cs_body);
        cell.setCellValue(teacher.getTareWeight());
        cell = row2.createCell(4);
        setCellStyleAndType(cell, cs_body);
        cell.setCellValue(teacher.getCargoWeight());
        cell = row2.createCell(5);
        cell.setCellStyle(cs_body);
        return rowNum;
    }

    private String[] querySumHeader(WeighLogQueryVO queryVO) {
        String headerStr = "";
        if ("poundNo".equals(queryVO.getDetailFlag())) {
            headerStr = "称重编号,车辆,毛重(KG),皮重(KG),净重(KG),称重时间";
        } else if (queryVO.getGroupBy().equals("goodsName")) {
            headerStr = "货物名称,批次号,毛重(KG),皮重(KG),净重(KG)";
        } else if (queryVO.getGroupBy().equals("license")) {
            headerStr = "车辆信息,批次号,毛重(KG),皮重(KG),净重(KG)";
        } else if (queryVO.getGroupBy().equals("shipNo")) {
            headerStr = "发货单位,批次号,毛重(KG),皮重(KG),净重(KG)";
        } else if (queryVO.getGroupBy().equals("customerCompanyName")) {
            headerStr = "收货单位,批次号,毛重(KG),皮重(KG),净重(KG)";
        } else if (queryVO.getGroupBy().equals("consignCompanyName")) {
            headerStr = "运输单位,批次号,毛重(KG),皮重(KG),净重(KG)";
        } else if (queryVO.getGroupBy().equals("remark")) {
            headerStr = "备注汇总,批次号,毛重(KG),皮重(KG),净重(KG)";
        } else if (queryVO.getGroupBy().equals("contractNo")) {
            headerStr = "合同号,批次号,毛重(KG),皮重(KG),净重(KG)";
        } else if (queryVO.getGroupBy().equals("flowDirectionName")) {
            headerStr = "货物流向,批次号,毛重(KG),皮重(KG),净重(KG)";
        } else if (queryVO.getGroupBy().equals("cntrNo")) {
            headerStr = "箱号汇总,批次号,毛重(KG),皮重(KG),净重(KG)";
        } else {
            headerStr = "箱型汇总,批次号,车辆,毛重(KG),皮重(KG),净重(KG)";
        }
        String[] header = headerStr.split(",");
        return header;
    }

    private WeighLogQueryVO getSumQueryVO(WeighLogQueryVO query, WeighLogInfoVO info) {
        //此处必须这么操作，为了不覆盖query查询条件
        WeighLogQueryVO queryVO = new WeighLogQueryVO();
        if (query.getGroupByConditionValue() != null) {
            queryVO.setGroupByConditionValue(query.getGroupByConditionValue());
        }
        BeanUtils.copyProperties(query, queryVO);
        if ("poundNo".equals(queryVO.getDetailFlag())) {
            if (StringUtils.isEmpty(info.getName())) {
                info.setName("");
            }
            //货物名称
            if (queryVO.getGroupBy().equals("goodsName")) {
                queryVO.setGoodsName(info.getName());
                queryVO.setCellName("货物名称");
                //车辆信息
            } else if (queryVO.getGroupBy().equals("license")) {
                queryVO.setLicense(info.getName());
                queryVO.setCellName("车辆信息");
                //发货单位
            } else if (queryVO.getGroupBy().equals("shipNo")) {
                queryVO.setShipNo(info.getName());
                queryVO.setCellName("发货单位");
                //收货单位
            } else if (queryVO.getGroupBy().equals("customerCompanyName")) {
                queryVO.setCustomerCompanyName(info.getName());
                queryVO.setCellName("收货单位");
                //运输单位
            } else if (queryVO.getGroupBy().equals("consignCompanyName")) {
                queryVO.setConsignCompanyName(info.getName());
                queryVO.setCellName("运输单位");
                //备注
            } else if (queryVO.getGroupBy().equals("remark")) {
                queryVO.setRemark(info.getName());
                queryVO.setCellName("备注");
                //合同号
            } else if (queryVO.getGroupBy().equals("contractNo")) {
                queryVO.setContractNo(info.getName());
                queryVO.setCellName("合同号");
                //货物流向
            } else if (queryVO.getGroupBy().equals("flowDirectionName")) {
                queryVO.setFlowDirectionName(info.getName());
                queryVO.setCellName("货物流向");
                //集装箱号
            } else if (queryVO.getGroupBy().equals("cntrNo")) {
                queryVO.setCntrNo(info.getName());
                queryVO.setCellName("集装箱号");
            } else {
                queryVO.setCntrSizeType(info.getName());
                queryVO.setCellName("箱型");
            }
            queryVO.setGroupBy("poundNo");
        }
        return queryVO;
    }

    @Override
    @Transactional
    public void modifyLicense(String truckId, String modifyLicense)
            throws DatabaseOperationFailedException {
        int num = weighDao.modifyWeighLogLicense(modifyLicense, Integer.parseInt(truckId));
        if (1 > num) {
            throw new DatabaseOperationFailedException(CommonCodeEnum.NOT_EXISTS.getCode(),
                    CommonCodeEnum.NOT_EXISTS.getMessage());
        }
        num = weighDao.modifyGateLogLicense(modifyLicense, Integer.parseInt(truckId));
        if (1 > num) {
            throw new DatabaseOperationFailedException(CommonCodeEnum.NOT_EXISTS.getCode(),
                    CommonCodeEnum.NOT_EXISTS.getMessage());
        }
        num = weighDao.modifyTruckInfoLicense(Integer.parseInt(truckId), modifyLicense);
        if (1 > num) {
            throw new DatabaseOperationFailedException(CommonCodeEnum.NOT_EXISTS.getCode(),
                    CommonCodeEnum.NOT_EXISTS.getMessage());
        }
        // TODO 开闸放行
    }


    public void updateWeight(Integer weighId, Integer truckId, String roughWeight, String tareWeight) {
        if (StrUtil.isNotBlank(roughWeight)) {
            Weightloginfo info = new Weightloginfo();
            info.setId(weighId);
            info.setWeight(Float.valueOf(roughWeight));
            weightloginfoMapper.updateById(info);
        }

        if (StrUtil.isNotBlank(tareWeight)) {
            Truckinfo truckInfo = new Truckinfo();
            truckInfo.setId(truckId);
            truckInfo.setTareWeight(Float.valueOf(tareWeight));
            truckinfoMapper.updateById(truckInfo);
        }
    }


    private void showWeightInfoOnLed(Weightloginfo info) {
        if(info.getLicense() == null){
            log.error("当前车牌号为空，无法在Led屏上显示信息");
            return;
        }
        try {
            WeighLedIpProperties.WeighChannelIp ledIp = WeighLedIpProperties.getLedIp(info.getWeightid());
            if (ledIp == null) {
                log.error("编号为{}地磅未配置屏幕Ip，当前车牌号为{}", info.getWeightid(), info.getLicense());
            } else {
                log.info("成功获取编号为{}地磅的Led屏幕Ip{}", info.getWeightid(), JSON.toJSONString(ledIp));
                if(StringUtils.isNotBlank(ledIp.getLeft())){
                    test.onPowerOnOff(ledIp.getLeft());
                    test.showThreeLine(ledIp.getLeft(), info.getLicense(), info.getWeight().toString() + "kg");
                }
                if(StringUtils.isNotBlank(ledIp.getRight())){
                    test.onPowerOnOff(ledIp.getRight());
                    test.showThreeLine(ledIp.getRight(), info.getLicense(), info.getWeight().toString() + "kg");
                }
            }
        } catch (Exception e) {
            log.error("访问编号为{}地磅led屏幕出现异常，当前车牌号为{}，异常原因为", info.getWeightid(), info.getLicense(), e);
        }
    }

    public void setWeightLogInfo(Weightloginfo info) {
        log.info("插入称重信息：{}", info);
        info.setVersion(0);
        info.setCreateTime(DateUtil.now());
        info.setUpdateTime(info.getCreateTime());
        //查询是否有未完成的车牌、重量,任务号一样的数据
        QueryWrapper<Weightloginfo>wrapper=new QueryWrapper<>();
        wrapper.eq("license",info.getLicense());
        wrapper.eq("weight",info.getWeight());
        wrapper.eq("task_no",info.getTaskNo());
        wrapper.eq("version",info.getVersion());
        wrapper.eq("state",0);
        //查询摄像头监控点编号
        Weightloginfo weightloginfo = weightloginfoMapper.selectOne(wrapper);
        if(weightloginfo!=null){
            FE.trueThrow(true, Msg.DB_ERROR, "同车辆同任务号已经存在过磅记录，请勿重复提交!");
        }
        //将称重信息展示到Led屏幕上
        showWeightInfoOnLed(info);
        try {
            info.setPicture(getUploadUrl(info));
        } catch (Exception e) {
            log.info( "海康网络不稳定，请稍后");
        }
        //根绝任务号查询notice_system,重进空出汽-驳 汽-场 空进重出 驳-汽 场-汽 散改集 场-汽(自提)  空-重-空 场-汽-驳 驳-汽-场
        //查询称重记录选择的任务是什么过磅类型
        //String noticeSystem=weighDao.selectNoticeSystemByTask(info.getTaskNo());
        String EIFO = "驳-汽,场-汽,散改集,场-汽（自提）";
        String EIFO1 = "场-汽-驳";
        String FIEO = "汽-驳,汽-场";
        String FIEO1 = "驳-汽-场";
        //空进重出
        if (EIFO.contains(info.getWorkProcessName()) || EIFO1.equals(info.getWorkProcessName())) {
            //info.setState(0);
            //车车取皮
            if ("1".equals(info.getTakeWay())) {
                if ("QM".equals(info.getOperateType())) {
                    //查询距离当前时间最近的一条取皮记录
                    WeighLogInfoVO vo1 = new WeighLogInfoVO();
                    vo1.setLicense(info.getLicense());
                    vo1.setWeighTime(DateUtil.now());
                    vo1.setTaskNo(info.getTaskNo());
                    vo1.setTakeWay(info.getTakeWay());
                    vo1.setVersion(0);
                    WeighLogInfoVO weighLogInfoVO = weighDao.queryWeighLogInfoQP(vo1);
                    if (weighLogInfoVO != null) {
                        weighLogInfoVO.setState(1);
                        weighDao.updateState(weighLogInfoVO.getId());
                        info.setTareWeight(weighLogInfoVO.getWeight());
                        info.setTareWeighTime(weighLogInfoVO.getWeighTime());
                        info.setCreator2(info.getCreator());
                        info.setCreator(weighLogInfoVO.getCreator());
                    }
                    info.setState(1);
                } else if ("QP".equals(info.getOperateType())) {
                    info.setState(0);
                    Map<String, Object> needTakeCard = isNeedTakeCard();

                    if(Integer.parseInt(needTakeCard.get("take_card").toString())==1 && needTakeCard.toString().contains(info.getCustomerCompanyName())){
                        QueryWrapper<Truckinfo>wrapper1=new QueryWrapper<>();
                        wrapper1.eq("license",info.getLicense());
                        wrapper1.eq("binding_status",1);
                        List<Truckinfo> truckinfos = truckinfoMapper.selectList(wrapper1);
                        if(CollectionUtils.isEmpty(truckinfos)){
                            takeCard(info);
                            String stationId1=null;
                            String usable=null;
                            Kv carMachineInfo = cardSendRobotServiceImpl.getCarMachineInfo(stationId1, StrUtil.isBlank(usable));
                            webSocket.sendOneMessage("hs02", JsonUtil.obj2String(carMachineInfo));
                        }
                    }
                }
            } else {
                //单次取皮
                if ("QM".equals(info.getOperateType())) {
                    //查询距离当前时间最近的一条取皮记录
                    WeighLogInfoVO vo1 = new WeighLogInfoVO();
                    vo1.setLicense(info.getLicense());
                    vo1.setWeighTime(DateUtil.now());
                    vo1.setTaskNo(info.getTaskNo());
                    vo1.setTakeWay(info.getTakeWay());
                    vo1.setVersion(0);
                    WeighLogInfoVO weighLogInfoVO = weighDao.queryWeighLogInfoQP(vo1);
                    if (weighLogInfoVO != null) {
                        weighLogInfoVO.setState(1);
                        weighDao.updateState(weighLogInfoVO.getId());
                        info.setTareWeight(weighLogInfoVO.getWeight());
                        info.setTareWeighTime(weighLogInfoVO.getWeighTime());
                        info.setCreator2(info.getCreator());
                        info.setCreator(weighLogInfoVO.getCreator());
                    }
                    info.setState(1);
                } else if ("QP".equals(info.getOperateType())) {
                    WeighLogInfoVO vo1 = new WeighLogInfoVO();
                    vo1.setLicense(info.getLicense());
                    vo1.setWeighTime(DateUtil.now());
                    vo1.setTaskNo(info.getTaskNo());
                    vo1.setVersion(0);
                    WeighLogInfoVO weighLogInfoVO = weighDao.queryWeighLogInfoQP(vo1);
                    if (weighLogInfoVO != null) {
                        FE.trueThrow(true, Msg.DB_ERROR, "相同任务号已经存在单次取皮记录!");
                    }
                    info.setState(0);
                }
            }

            //重进空出
        } else if (FIEO.contains(info.getWorkProcessName()) || FIEO1.equals(info.getWorkProcessName())) {
            if ("QP".equals(info.getOperateType())) {
                //查询距离当前时间最近的一条取毛记录
                WeighLogInfoVO vo1 = new WeighLogInfoVO();
                vo1.setLicense(info.getLicense());
                vo1.setWeighTime(DateUtil.now());
                vo1.setTaskNo(info.getTaskNo());
                vo1.setVersion(0);
                WeighLogInfoVO weighLogInfoVO = weighDao.queryWeighLogInfoQM(vo1);
                if (weighLogInfoVO != null) {
                    weighDao.updateState(weighLogInfoVO.getId());
                    weighLogInfoVO.setTareWeight(info.getTareWeight());
                    weighLogInfoVO.setTareWeighTime(DateUtil.now());
                    weighLogInfoVO.setCreator2(info.getCreator());
                    weighDao.updateTareWeigh(weighLogInfoVO);
                    info.setState(1);
                }
            } else if ("QM".equals(info.getOperateType())) {
                info.setState(0);
                Map<String, Object> needTakeCard = isNeedTakeCard();
                if(Integer.parseInt(needTakeCard.get("take_card").toString())==1 && needTakeCard.get("company").toString().contains(info.getCustomerCompanyName())){
                    //判断车辆是否有已绑定的采集卡,如果有就不弹卡，没有就弹卡
                    QueryWrapper<Truckinfo>wrapper1=new QueryWrapper<>();
                    wrapper1.eq("license",info.getLicense());
                    wrapper1.eq("binding_status",1);
                    List<Truckinfo> truckinfos = truckinfoMapper.selectList(wrapper1);
                    if(CollectionUtils.isEmpty(truckinfos)){
                        takeCard(info);
                        String stationId1=null;
                        String usable=null;
                        Kv carMachineInfo = cardSendRobotServiceImpl.getCarMachineInfo(stationId1, StrUtil.isBlank(usable));
                        webSocket.sendOneMessage("hs02", JsonUtil.obj2String(carMachineInfo));
                    }
                }
                if (info.getTareWeight() != null) {
                    info.setTareWeight(null);
                }
            }
         }
//        Object isSaving = RedisUtils.getCacheObject("is_sgggg");
//        if(isSaving==null){
//            RedisUtils.setCacheObject("is_sgggg", "");
//        }
        var n = weightloginfoMapper.insert(info);
//        RedisUtils.deleteKeys("is_sgggg");
        FE.trueThrow(n != 1, Msg.DB_ERROR, "set WeightLogInfo add failed!");
    }
    public void takeCard(Weightloginfo info){
        List<CardSenderRobotInfoDO> cardSenderRobots = cardSenderRobotDao.queryStationIdByWeightNo(info.getWeightid()); //根据磅房获取发卡机信息
        log.info("对应磅房{} 找到{} 个发卡模组", info.getWeightid(), cardSenderRobots.size());
        for (CardSenderRobotInfoDO robot : cardSenderRobots) {
            String stationId = robot.getStationId();
            // 判断该发卡机是否登录，是否有卡可发
            CardMachine cm = CardMachineInData.cardMachineMap.get(stationId); // 获取发卡机实例
            if (cm == null || cm.getUsableSlotCard() == null || cm.getUsableSlotCard().size() <= 0 || cm.getType() == null) {
                String msg = StrUtil.format("弹卡失败：发卡机没登录，或无卡，或无法判断类别: {}", stationId);
                log.warn(msg);
                continue; // 该发卡机没有登录，或者无可用卡
            }
            if (cm.getType() == CardMachineParamUtil.CMConsts.CARD_MACHINE_TYPE_OUT) {
                String msg = StrUtil.format("弹卡失败：该模组{} 是出门模组", stationId);
                log.warn(msg);
                continue; // 该发卡机没有登录，或者无可用卡
            }
            log.info("进闸发卡机准备弹卡： {}({})", stationId, robot.getType());
            String cardId = CardMachineInData.popCardGetCardId(cm); // 弹卡
            if (StrUtil.isBlank(cardId)) {
                String msg = StrUtil.format("弹卡失败：发卡机弹卡失败: {}", stationId);
                log.warn(msg);
                continue; // 此机柜弹卡出问题，继续循环
            }
            if (cardId.length() < cardIdCorrectNum) {
                cardId = "3" + cardId;
            }
            log.info("进闸发卡机弹卡成功： {} -> {}", stationId, cardId);


            // 弹卡成功，绑定车牌和卡号，并更新到数据库
            Truckinfo ti = new Truckinfo();
            ti.setLicense(info.getLicense());
            ti.setBindingStatus(Constants.BINDING_STATUS_ON);
            ti.setTagid(cardId);
            ti.setState(12);
            ti.setInTime(cn.hutool.core.date.DateUtil.now());
            //查询最新一条进闸的数据任务
            Integer truckId=iGateDao.selectLastGateInByLicense(info.getLicense());
            UpdateWrapper<Truckinfo>wrapper=new UpdateWrapper<>();
            wrapper.eq("id",truckId);
            wrapper.set("binding_status",Constants.BINDING_STATUS_ON);
            wrapper.set("tagid",cardId);
            truckinfoMapper.update(null,wrapper);
            log.info("绑定卡号和车牌，更新完成： {} <-> {}", cardId, ti.getLicense());
            break;
    }
    }

    public  Map<String, Object> isNeedTakeCard() {
        Map<String, Object> needTakeCard = weighDao.isNeedTakeCard();

        return needTakeCard;
    }

    public void editweighloginfo(Weightloginfo info) {
        log.info("更新称重信息：{}", info);
        info.setUpdateTime(DateUtil.now());
        var n = weightloginfoMapper.updateById(info);
        FE.trueThrow(n != 1, Msg.DB_ERROR, "set WeightLogInfo update failed!");
    }

    public String upload(MultipartFile multipartFile) {
        ObjectWriteResponse res = minioTemplate.putObject(multipartFile);
        String path = res.object();
        String url = minioTemplate.getObject(path);
        String s = StringUtils.substringBefore(url, "?");
        return s;
    }

    /**
     * url转MultipartFile
     *
     * @url:图片URL
     * @fileName:文件名
     * @return:返回的文件
     */
    public static MultipartFile urlToMultipartFile(String url, String fileName) throws Exception {
        File file = null;
        MultipartFile multipartFile = null;
        try {
            SSLContext context = createIgnoreVerifySSL();
            HttpsURLConnection httpUrl = (HttpsURLConnection) new URL(url).openConnection();
            httpUrl.setSSLSocketFactory(context.getSocketFactory());
            httpUrl.connect();
            file = inputStreamToFile(httpUrl.getInputStream(), fileName);
            multipartFile = fileToMultipartFile(file);
            httpUrl.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return multipartFile;
    }

    /**
     * 绕过验证
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     */
    public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSL");

        // 实现一个X509TrustManager接口，用于绕过验证，不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[]{trustManager}, null);
        return sc;
    }


    public static File inputStreamToFile(InputStream ins, String name) throws Exception {
        File file = new File(System.getProperty("java.io.tmpdir") + File.separator + name);
        OutputStream os = new FileOutputStream(file);
        int len = 8192;
        byte[] buffer = new byte[len];
        int bytesRead;
        while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        return file;
    }


    public static MultipartFile fileToMultipartFile(File file) {
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(16, null);
        FileItem item = diskFileItemFactory.createItem(file.getName(), "image/png", true, file.getName());
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        try {
            FileInputStream fis = new FileInputStream(file);
            OutputStream os = item.getOutputStream();
            int len = 8192;
            while ((bytesRead = fis.read(buffer, 0, len)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }


    private static final String ARTEMIS_PATH = "/artemis";

    public static String myToken = "";

    public String getToken() {
        ArtemisConfig config = new ArtemisConfig("192.168.90.2", appKey, appSecret);
        artemisConfig = config;
        final String getSecurityApi = ARTEMIS_PATH + "/oauth/token"; // 接口路径
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getSecurityApi);
            }
        };
        Map<String, String> querys = new HashMap();//get 请求的查询参数
        String result = null;
        try {
            result = ArtemisHttpUtil.doPostFormArtemis(artemisConfig, path, null, querys,
                    null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("appKey={}", appKey);
        log.info("appSecret={}", appSecret);
        log.info("getToken:result={}", result);
        JSONObject object = JSONObject.parseObject(result);
        String token = "";
        if (object != null) {
            token = object.getString("access_token");
        }
        return token;
    }


    public List<WeightLogMin> getReportWeightLog(String license, String taskNo, String btime, String etime) {
        var lst = weightLogMinMapper.selectList(new QueryWrapper<WeightLogMin>()
                        .gt("create_time", btime)
//                .lt("create_time", etime)
                        .eq("license", license)
                        .eq("task_no", taskNo)
                        .orderByDesc("id")
        );
        return lst;
    }


    public List<LicenseDto> selectLicenseMq(LicenseDto info) {
        return weighDao.selectLicenseMq(info);
    }

    public void deleteLicenseMq(LicenseDto info) {
        weighDao.deleteLicenseMq(info);
    }

    public void deleteAllLicenseMq(LicenseDto info) {
        weighDao.deleteAllLicenseMq(info);
    }

    public List<String> selectWeighLogLicense() {
        return weighDao.selectWeighLogLicense();
    }

    @Override
    public CommonVO<Map<String, List<String>>> queryWeightSumCondition() {
        List<WeighLogInfoVO> list = weighDao.queryWeighSumConditionList();
        Map<String, List<String>> result = new HashMap<>();
        result.put("license", list.stream().filter(item -> StringUtils.isNotEmpty(item.getName()) && item.getOperateType().equals("license")).map(WeighLogInfoVO::getName).distinct().collect(Collectors.toList()));
        result.put("customerCompanyName", list.stream().filter(item -> StringUtils.isNotEmpty(item.getName()) && item.getOperateType().equals("customerCompanyName")).map(WeighLogInfoVO::getName).distinct().collect(Collectors.toList()));
        result.put("consignCompanyName", list.stream().filter(item -> StringUtils.isNotEmpty(item.getName()) && item.getOperateType().equals("consignCompanyName")).map(WeighLogInfoVO::getName).distinct().collect(Collectors.toList()));
        result.put("shipNo", list.stream().filter(item -> StringUtils.isNotEmpty(item.getName()) && item.getOperateType().equals("shipNo")).map(WeighLogInfoVO::getName).distinct().collect(Collectors.toList()));
        result.put("contractNo", list.stream().filter(item -> StringUtils.isNotEmpty(item.getName()) && item.getOperateType().equals("contractNo")).map(WeighLogInfoVO::getName).distinct().collect(Collectors.toList()));
        result.put("cntrSizeType", list.stream().filter(item -> StringUtils.isNotEmpty(item.getName()) && item.getOperateType().equals("cntrSizeType")).map(WeighLogInfoVO::getName).distinct().collect(Collectors.toList()));
        result.put("cntrNo", list.stream().filter(item -> StringUtils.isNotEmpty(item.getName()) && item.getOperateType().equals("cntrNo")).map(WeighLogInfoVO::getName).distinct().collect(Collectors.toList()));
        result.put("remark", list.stream().filter(item -> StringUtils.isNotEmpty(item.getName()) && item.getOperateType().equals("remark")).map(WeighLogInfoVO::getName).distinct().collect(Collectors.toList()));
        result.put("poundNo", list.stream().filter(item -> StringUtils.isNotEmpty(item.getName()) && item.getOperateType().equals("poundNo")).map(WeighLogInfoVO::getName).distinct().collect(Collectors.toList()));
        result.put("goodsName", list.stream().filter(item -> StringUtils.isNotEmpty(item.getName()) && item.getOperateType().equals("goodsName")).map(WeighLogInfoVO::getName).distinct().collect(Collectors.toList()));
        CommonVO<Map<String, List<String>>> resultCommonVO = new CommonVO<>();
        resultCommonVO.setData(result);
        return resultCommonVO;
    }

    @Override
    public Map query(String licence) {
        Map map = new HashMap();
        List<QueryMessageVO> weightloginfo = weighDao.query(licence);
        List<QueryWhiteVO> whiteVO = weighDao.queryByLicense(licence);
        map.put("weightloginfo",weightloginfo);
        map.put("whiteVO",whiteVO);
        return map;
    }


    /**
     * 根据车牌查询对应的采集卡，如果标签为空直接返回，不为空查询采集卡对应的标签id，再根据磅房编号查询对应的基站id（用逗号分隔），返回给前端
     *
     * @param info
     * @return
     */
    public Map<String, String> isBindTag(Map<String, String> info) {
        Map<String, String> returnMap = new HashMap<>();
        //查询车牌是否绑定了标签id
        String license = info.get("license");
        String weightId = info.get("weightId");
        String cardId = weighDao.selectTruckInfo(license);
        if (cardId == null) {
            returnMap.put("tagId", null);
            returnMap.put("station", null);
        } else {
            String stationId = weighDao.selectStationId(weightId);
            String tagId = weighDao.selectTagIdByCard(cardId);
            returnMap.put("tagId", tagId);
            returnMap.put("station", stationId);
        }
        return returnMap;

    }

    @Autowired
    private WeightloginfoDeleteMapper weightloginfoDeleteMapper;

    public CommonVO<Object> deleteWeigh(Long id) {
        Weightloginfo weightloginfo = weightloginfoMapper.selectById(id);
        WeightloginfoDelete weightloginfoDelete = new WeightloginfoDelete();
        BeanUtils.copyProperties(weightloginfo, weightloginfoDelete);
        //把需要删除的完整记录剪切到另一张表
        weightloginfoDelete.setId(null);
        weightloginfoDeleteMapper.insert(weightloginfoDelete);
        weightloginfoMapper.deleteById(id);
        return new CommonVO<>();
    }

    public void addweighloginfo(Weightloginfo info) {
        log.info("插入补录信息：{}", info);
        info.setCreateTime(info.getGrossWeighTime());
        info.setUpdateTime(info.getGrossWeighTime());
        info.setCreator2(info.getCreator());
        var n = weightloginfoMapper.insert(info);

        FE.trueThrow(n != 1, Msg.DB_ERROR, "set WeightLogInfo add failed!");

    }

    public Float selectWeightByOhtherWeight(Weightloginfo info) {
        //根绝任务号查询notice_system,重进空出汽-驳 汽-场 空进重出 驳-汽 场-汽 散改集 场-汽(自提)  空-重-空 场-汽-驳 驳-汽-场
        //查询称重记录选择的任务是什么过磅类型
//        String EIFO = "驳-汽,场-汽,散改集,场-汽（自提）,场-汽-驳";
        String EIFO = "驳-汽,场-汽,散改集,场-汽（自提）";
        String EIFO1 = "场-汽-驳";
        String FIEO = "汽-驳,汽-场";
        String FIEO1 = "驳-汽-场";
        //空进重出
        if (info.getWorkProcessName() == null) {
            return null;
        }

        if (EIFO.contains(info.getWorkProcessName()) || EIFO1.equals(info.getWorkProcessName())) {
            //车车取皮
            if ("1".equals(info.getTakeWay())) {
                if ("QM".equals(info.getOperateType())) {
                    //查询距离当前时间最近的一条取皮记录
                    WeighLogInfoVO vo1 = new WeighLogInfoVO();
                    vo1.setLicense(info.getLicense());
                    vo1.setWeighTime(DateUtil.now());
                    vo1.setTaskNo(info.getTaskNo());
                    vo1.setTakeWay(info.getTakeWay());
                    vo1.setVersion(0);
                    WeighLogInfoVO weighLogInfoVO = weighDao.queryWeighLogInfoQP(vo1);
                    if (weighLogInfoVO != null) {
                        return weighLogInfoVO.getWeight();
                    }
                }
            } else {
                //单次取皮
                if ("QM".equals(info.getOperateType())) {
                    //查询距离当前时间最近的一条取皮记录
                    WeighLogInfoVO vo1 = new WeighLogInfoVO();
                    vo1.setLicense(info.getLicense());
                    vo1.setWeighTime(DateUtil.now());
                    vo1.setTaskNo(info.getTaskNo());
                    vo1.setTakeWay(info.getTakeWay());
                    vo1.setVersion(0);
                    WeighLogInfoVO weighLogInfoVO = weighDao.queryWeighLogInfoQP(vo1);
                    if (weighLogInfoVO != null) {
                        return weighLogInfoVO.getWeight();
                    }
                }
            }

            //重进空出
        } else if (FIEO.contains(info.getWorkProcessName()) || FIEO1.equals(info.getWorkProcessName())) {
            if ("QP".equals(info.getOperateType())) {
                //查询距离当前时间最近的一条取毛记录
                WeighLogInfoVO vo1 = new WeighLogInfoVO();
                vo1.setLicense(info.getLicense());
                vo1.setWeighTime(DateUtil.now());
                vo1.setTaskNo(info.getTaskNo());
                vo1.setTakeWay(info.getTakeWay());
                vo1.setVersion(0);
                WeighLogInfoVO weighLogInfoVO = weighDao.queryWeighLogInfoQM(vo1);
                if (weighLogInfoVO != null) {
//                    return info.getGrossWeight();
                    return weighLogInfoVO.getGrossWeight();
                }
            }
        }
        return null;
    }

    @Autowired
    private RestTemplate restTemplate;

    @Value("${raster-url}")
    private String rasterUrl;

    public CommonVO<Object> rasterShelter() throws IOException, InterruptedException {
        Boolean returnMessage = true;
        //向光栅查询是否遮挡
//        DateTime date = DateUtil.date();
//        Raster raster = new Raster();
//        raster.setSend("00 00 00 07 00 06 01 03 00 07 00 01");
//        raster.setCreateTime(date);
//        raster.setUpdateTime(date);
//        weighDao.insertRaster(raster);
//        String replace = raster.getSend().replace(" ", "");
//        byte[] bytes = HexUtil.Hex2Bytes(replace);
//        JSONObject postData = new JSONObject();
//        postData.put("data", new String(bytes));
//        restTemplate.postForEntity(rasterUrl, postData, JSONObject.class).getBody();
//
//        //  00 00 00 07 00 05 01 03 02 00 00
//        Raster raster1 = new Raster();
//        raster1.setSend("00 00 00 08 00 06 01 03 00 08 00 01");
//        raster1.setCreateTime(date);
//        raster1.setUpdateTime(date);
//        weighDao.insertRaster(raster1);
//        String replace1 = raster1.getSend().replace(" ", "");
//        byte[] bytes1 = HexUtil.Hex2Bytes(replace1);
//        JSONObject postData1 = new JSONObject();
//        postData1.put("data", new String(bytes1));
//        restTemplate.postForEntity(rasterUrl, postData1, JSONObject.class).getBody();
//        // 00 00 00 08 00 05 01 03 02 00 00
//        //等待2s查询最新数据
//        long time = date.getTime();
//        Date endDate = new Date(time + 1000L * 5);
//        raster.setCreateTime(date);
//        raster.setUpdateTime(endDate);
//        raster1.setCreateTime(date);
//        raster1.setUpdateTime(endDate);
//        for (int i = 0; i < 5; i++) {
//            Thread.sleep(1000);
//            Raster rasterReturn = weighDao.selectRaster(raster);
//            Raster raster1Return = weighDao.selectRaster(raster1);
//            if (raster1Return != null && rasterReturn != null) {
//                if ("00 00 00 07 00 05 01 03 02 00 00".equals(rasterReturn.getResponse()) && "00 00 00 08 00 05 01 03 02 00 00".equals(raster1Return.getResponse())) {
//                    returnMessage = false;
//                    break;
//                } else {
//                    break;
//                }
//            }
//        }
        return new CommonVO<Object>(returnMessage);
    }


    public float queryLastWeight(Weightloginfo info) {
        WeighLogInfoVO vo = new WeighLogInfoVO();
        vo.setLicense(info.getLicense());
        vo.setTakeWay(info.getTakeWay());
        vo.setVersion(1);
        WeighLogInfoVO resp = new WeighLogInfoVO();
        if ("0".equals(info.getTakeWay())) {
            resp = weighDao.selectLastQP(vo);
        } else {
            resp = weighDao.selectLastNoState(vo);
        }

        if (resp == null) {
            return 0;
        } else {
            return resp.getWeight();
        }
    }


    public void setWeighloginfoWithoutTask(Weightloginfo info) throws Exception {
        info.setVersion(1);
        log.info("插入称重信息单机版：{}", info);
        if("1".equals(info.getTakeWay())){
            QueryWrapper<Weightloginfo>wrapper=new QueryWrapper<>();
            wrapper.eq("license",info.getLicense());
            wrapper.eq("weight",info.getWeight());
            wrapper.eq("version",info.getVersion());
            wrapper.eq("take_way",1);
            wrapper.eq("state",0);
            Weightloginfo weightloginfo = weightloginfoMapper.selectOne(wrapper);
            if(weightloginfo!=null){
                FE.trueThrow(true, Msg.DB_ERROR, "同车辆已经存在过磅记录，请勿重复提交!");
            }
        }
        //将称重信息展示到Led屏幕上
        showWeightInfoOnLed(info);
        //查询摄像头监控点编号
        info.setCreateTime(DateUtil.now());
        //获取当时的监控图片地址
        try {
            info.setPicture(getUploadUrl(info));
        } catch (Exception e) {
            log.info( "海康网络不稳定，请稍后");
        }

        if ("pass".equals(info.getReportResult())) {
            var n = weightloginfoMapper.insert(info);
            FE.trueThrow(n != 1, Msg.DB_ERROR, "set WeightLogInfo add failed!");

        }

        if (info.getWeight() == 0) {
            FE.trueThrow(true, Msg.DB_ERROR, "重量为0无法保存!");
        }

        //配对模式
        WeighLogInfoVO vo = new WeighLogInfoVO();
        vo.setVersion(1);
        if ("1".equals(info.getTakeWay())) {
            vo.setLicense(info.getLicense());
            vo.setTakeWay("1");
            //先查看该车牌此前是否有未完成记录，如果没有，则把重量赋值给weigh字段上新增，如果有未完成的，则把这个未完成变成已完成，再把
            WeighLogInfoVO resp = weighDao.selectLastNoState(vo);
            if (resp == null) {
                info.setState(0);
                if (info.getWeight() > 30000) {
                    info.setOperateType("QM");
                    info.setGrossWeighTime(DateUtil.now());
                    info.setGrossWeight(info.getWeight());
                } else {
                    info.setOperateType("QP");
                    info.setTareWeight(info.getWeight());
                    info.setTareWeighTime(DateUtil.now());
                }
                var n = weightloginfoMapper.insert(info);
                FE.trueThrow(n != 1, Msg.DB_ERROR, "set WeightLogInfo add failed!");
            } else {
                if (1 == resp.getState()) {
                    info.setState(0);
                    if (info.getWeight() > 30000) {
                        info.setOperateType("QM");
                        info.setGrossWeighTime(DateUtil.now());
                        info.setGrossWeight(info.getWeight());
                    } else {
                        info.setOperateType("QP");
                        info.setTareWeight(info.getWeight());
                        info.setTareWeighTime(DateUtil.now());
                    }
                    var n = weightloginfoMapper.insert(info);
                    FE.trueThrow(n != 1, Msg.DB_ERROR, "set WeightLogInfo add failed!");
                } else {
                    //前端的重量大于库里的
                    if (info.getWeight() > resp.getWeight()) {
                        WeighLogInfoVO req = new WeighLogInfoVO();
                        req.setId(resp.getId());
                        req.setOperateType("QP");
                        req.setGrossWeight(null);
                        req.setGrossWeighTime(null);
                        req.setTareWeight(resp.getWeight());
                        req.setTareWeighTime(resp.getWeighTime());
                        req.setState(1);
                        weighDao.updateLastWeigh(req);
                        info.setOperateType("QM");
                        info.setGrossWeight(info.getWeight());
                        info.setGrossWeighTime(info.getCreateTime());
                        info.setTareWeight(resp.getWeight());
                        info.setTareWeighTime(resp.getWeighTime());
                        info.setCreator2(info.getCreator());
                        info.setCreator(resp.getCreator());

                    } else {
                        WeighLogInfoVO req = new WeighLogInfoVO();
                        req.setId(resp.getId());
                        req.setOperateType("QM");
                        req.setGrossWeight(resp.getWeight());
                        req.setGrossWeighTime(resp.getWeighTime());
                        req.setTareWeight(info.getWeight());
                        req.setTareWeighTime(info.getCreateTime());
                        req.setState(1);
                        req.setCreator2(info.getCreator());
                        weighDao.updateLastWeigh(req);
                        info.setOperateType("QP");
                        info.setTareWeight(info.getWeight());
                        info.setTareWeighTime(info.getCreateTime());
                    }

                    info.setState(1);
                    var n = weightloginfoMapper.insert(info);
                    FE.trueThrow(n != 1, Msg.DB_ERROR, "set WeightLogInfo add failed!");
                }
            }
        }
        //单次取皮过毛重，
        if ("0".equals(info.getTakeWay()) && "QM".equals(info.getOperateType())) {
            vo.setLicense(info.getLicense());
            vo.setTakeWay("0");
            //查询当前车最新皮重
            WeighLogInfoVO weighLogInfoVO1 = weighDao.queryWeighLogInfoQPLast(vo);
            if (weighLogInfoVO1 != null) {
                info.setTareWeight(weighLogInfoVO1.getWeight());
                info.setTareWeighTime(weighLogInfoVO1.getWeighTime());
                info.setGrossWeight(info.getWeight());
                info.setGrossWeighTime(info.getCreateTime());
                info.setCreator2(info.getCreator());
                info.setCreator(weighLogInfoVO1.getCreator());
                info.setState(1);
                var n = weightloginfoMapper.insert(info);
                FE.trueThrow(n != 1, Msg.DB_ERROR, "set WeightLogInfo add failed!");
            }

        }

        //单纯存皮重
        if ("0".equals(info.getTakeWay()) && "QP".equals(info.getOperateType())) {
            info.setState(0);
            info.setTareWeight(info.getWeight());
            info.setTareWeighTime(info.getCreateTime());
            var n = weightloginfoMapper.insert(info);
            FE.trueThrow(n != 1, Msg.DB_ERROR, "set WeightLogInfo add failed!");
        }

    }

    private String getUploadUrl(Weightloginfo info) throws Exception {
        String weightid = info.getWeightid();
        Integer direction = info.getDirection();
        Map map = new HashMap();
        map.put("weightid", weightid);
        map.put("direction", direction);
        AreaVideoVO vo = cameraDao.queryVideoListV2(map);
        List<CameraVO> videoList = vo.getVideoList();
        CameraVO cameraVO = videoList.get(0);
        myToken = getToken();
        log.info("setWeightLogInfo:token:" + myToken);
        final String getSecurityApi = ARTEMIS_PATH + "/api/video/v1/manualCapture"; // 接口路径
        Map<String, String> path = new HashMap<String, String>(2) {
            {
                put("https://", getSecurityApi);
            }
        };
        Map<String, String> head = new HashMap<String, String>(2) { //get 请求的 header 参数
            {
                put("access_token", myToken);
                put("Content-Type", "application/json");
                put("headpost", "sky-test");
            }
        };
        Map<String, Object> body = new HashMap();//get 请求的查询参数
        body.put("cameraIndexCode", cameraVO.getCode());
        Map<String, String> querys = new HashMap();//get 请求的查询参数
        String result = null;

        result = ArtemisHttpUtil.doPostStringArtemis(artemisConfig, path, JSONObject.toJSONString(body), querys,
                null, "application/json", head);

        log.info("setWeightLogInfo:result={}", result);
        JSONObject object = JSONObject.parseObject(result);
        String data = "";
        if (object != null) {
            data = object.getString("data");
            log.info("queryCameraVideoList:data={}", data);
        }
        String upload = "";
        if (!StringUtils.isEmpty(data)) {
            JSONObject url = JSONObject.parseObject(data);
            String urlStr = url.getString("picUrl");
            UUID uuid = UUID.randomUUID();
            MultipartFile multipartFile = urlToMultipartFile(urlStr, uuid + ".png");
            upload = upload(multipartFile);
            log.info("文件上传服务器转换后的地址：" + upload);
        }
        return upload;
    }

    /**
     * 导出数据预览
     *
     * @param queryVO
     * @throws Exception
     */
    public PageResult<WeighLogInfoVO> onlineShowExcelPreview(PageInput<WeighLogQueryVO> queryVO) {
        //预览显示专用
        getSumWhereValueCondition(queryVO.getData());
        getSumWhereShowDetail(queryVO.getData());
        int total = weighDao.queryWeighLogSumDetailListCount(queryVO.getData());
        PageResult<WeighLogInfoVO> result = new PageResult<>(queryVO.getCurPage(), queryVO.getPageSize(), total);
        List<WeighLogInfoVO> data = weighDao.queryWeighLogSumDetailListPage(result.getStartIndex(), result.getPageSize(),
                queryVO.getData());
        for (WeighLogInfoVO entry : data) {
            if (Objects.isNull(entry.getTimeLong()) && !StringUtils.isEmpty(entry.getGrossWeighTime())) {
                entry.setWeighTime(entry.getGrossWeighTime());
                continue;
            }
            if (Objects.isNull(entry.getTimeLong()) && !StringUtils.isEmpty(entry.getTareWeighTime())) {
                entry.setWeighTime(entry.getTareWeighTime());
                continue;
            }
            if (!Objects.isNull(entry.getTimeLong()) && entry.getTimeLong().intValue() <= 0) {
                entry.setWeighTime(entry.getGrossWeighTime());
                continue;
            }
            if (!Objects.isNull(entry.getTimeLong()) && entry.getTimeLong().intValue() > 0) {
                entry.setWeighTime(entry.getTareWeighTime());
                continue;
            }
        }
        if (0 < total) {
            result.setData(data);
        }
        return result;
    }

    public CommonVO<Object> acceptRasterShelter(String raster) {
        Raster raster1 = new Raster();
        raster1.setResponse(raster);
        raster1.setUpdateTime(DateUtil.date());
        String substring = raster.substring(0, 11);
        raster1.setSplit(substring);
        weighDao.updateRaster(raster1);
        return new CommonVO<>();
    }

    public Integer selectTruckTagStatus(String license) {
        //查询当前是否有未还卡的
        Integer status1 =weighDao.selectTruckTagStatusNotReturn(license);
        if (status1!=null && status1==1){
            return status1;
        }
        Integer status =weighDao.selectTruckTagStatus(license);
        //如果没有绑定的，返回FALSE 未取卡
        if(status==null){
            return 0;
        }
        return status;

    }

    public Integer updateTruckTagStatus(String license) {
        //把该车的卡解绑
        weighDao.updateTruckTagStatus(license);

        Integer status =weighDao.selectTruckTagStatus(license);
        //如果没有绑定的，返回FALSE 未取卡
        if(status==null){
            return 0;
        }
        return status;
    }
}
